import axios from 'axios';
import Vue from 'vue';
import Config from './config';

const ajax = axios.create({
    baseURL: Config.remoteServiceBaseUrl,
    timeout: 30000,
});

ajax.interceptors.request.use(config => {
    if (!!window.abp.auth.getToken()) {
        config.headers.common['Authorization'] = 'Bearer ' + window.abp.auth.getToken();
    }
    if (window.abp.content_disposition !== '') {
        config.headers.common['Content-Disposition'] = window.abp.content_disposition;
    }
    if (window.abp.content_range !== '') {
        config.headers.common['Content-Range'] = window.abp.content_range;
    }
    config.headers.common['.AspNetCore.Culture'] = window.abp.utils.getCookieValue('Abp.Localization.CultureName');
    return config;
}, error => {
    return Promise.reject(error);
});

const vm = new Vue({});

ajax.interceptors.response.use(response => {
    return response;
}, error => {
    if (!!error.response && !!error.response.data.error && !!error.response.data.error.message && error.response.data.error.details) {


        vm.$Message.error({
            background: true,
            content: error.response.data.error.details,
            duration: 0,
        });

    } else if (!!error.response && !!error.response.data.error && !!error.response.data.error.message) {


        vm.$Message.error({
            background: true,
            content: error.response.data.error.message,
            duration: 0,
        });

    } else if (!error.response) {


        vm.$Message.error({
            background: true,
            content: '对不起，发生了未知错误，请联系管理员',
            duration: 0,
        })

    }
    setTimeout(() => {
        vm.$Message.destroy();
    }, 3000);
    return Promise.reject(error);
});

export default ajax;
